<template>
  <div>
    <!-- //面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="roleslist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <!-- 插槽 -->
          <template slot-scope='scope'>
            <!-- 栅格栏 -->
            <el-row v-for="(item,il) in scope.row.children" :key='item.id'
              :class="['bdbottom',il===0?'bdtop':'','vcenter','test'] ">
              <!-- 一级 -->
              <el-col :span="5">
                <el-tag  closable @close="removeRightById(scope.row,item.id)" >{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级 -->
              <el-col :span="19">
                <el-row v-for="(item2,il2) in item.children" :key='item2.id'
                 :class="[il2===0?'':'bdtop','vcenter']"  >
                  <!-- 二级 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)" >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3,il3) in item2.children" :key='item3.id' closable
                      @close="removeRightById(scope.row,item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名字" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope='scope'>
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click='showSetrole(scope.row)' >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分配权限对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="setRightDialogVisible"
        width="50%" @close="closeRoleTree()" >
        <!-- 树形控件 -->
        <el-tree :data="rightlist" :props="treeProps"
        show-checkbox node-key="id" default-expand-all
        :default-checked-keys="defKeys" ref='treeRef'  ></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights" >确 定</el-button>
        </span>
      </el-dialog>


    </el-card>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        //角色列表数据
        roleslist: [],
        //控制分配角色对话框展开折叠
        setRightDialogVisible:false,
        //所有权限数据
        rightlist:[],
        //树形控件的属性绑定对象
        treeProps:{
          label:'authName',
          children:'children'
        },
        // 默认选择结点的id值数组
        defKeys:[],
        //即将分配权限的id
        roleId:''
      }
    },
    created() {
      this.getRolesList()
    },
    methods: {
      //请求角色列表数据
      async getRolesList() {
        const {
          data: res
        } = await this.$http.get('roles')
        if (res.meta.status !== 200) return this.$message.error('获取角色列表数据失败！')
        this.roleslist = res.data
        // console.log(this.roleslist,'角色列表数据');
      },
      // 根据id移除权限
      async removeRightById(role,rightId) {
        // 弹框提示
        const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)

        if(confirmResult!=='confirm') return this.$message.info('取消了删除')
        console.log('删除成功');
        const {data:res}=await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if(res.meta.status!==200) return this.$message.error('删除权限失败')
        // 删除成功后不建议刷新列表，因为页面会折叠。返回值里面的data是最新值，所以直接赋值就好了
        role.children=res.data
      },
      //分配权限对话框显示与隐藏
      async showSetrole(role){
        this.roleId=role.id
        //在对话框出来前获取全部权限数据
        const {data:res}=await this.$http.get('rights/tree')
        if(res.meta.status!==200) return this.$message.error('获取权限数据失败')
        //保存数据
        this.rightlist=res.data
        // console.log(this.rightlist);
        // 递归获取三级结点id
        this.getThirdKey(role,this.defKeys)
        // 展开对话框
        this.setRightDialogVisible=true
      },
      // 通过递归获取角色下所有三级权限的id数组,node结点，arr数组
      getThirdKey(node,arr){
        // 不包含children属性的为三级结点。添加到数组
        if(!node.children) return arr.push(node.id)
        // 开始递归
        node.children.forEach(item=>{
          this.getThirdKey(item,arr)
        })
      },
      //监听分配权限对话框的关闭事件
      closeRoleTree(){
        this.defKeys=[]
      },
      //确定后为角色分配权限
      async allotRights(){
        const keys=[
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        console.log('节点id',keys);
        const idStr=keys.join(',')
        
        const {data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
        if(res.meta.status!==200) return this.$message.error('更新权限失败')
        
        //成功，刷新列表，对话框折叠，提示
        this.$message.success('更新权限成功！')
        this.getRolesList()
        this.setRightDialogVisible=false
      },
    }
  }
</script>

<style lang="less" scoped>
  // .el-table{
  //   padding: 20px;
  // }
  .el-tag {
    margin: 7px;
  }

  .bdtop {
    border-top: 1px solid #eee;
  }

  .bdbottom {
    border-bottom: 1px solid #eee;
  }

  .vcenter {
    display: flex;
    align-items: center;
  }

  .test {
    text-align: center;
  }
</style>
